#pragma once
#include "Data.hpp"
#include "httplib.h"
#include <Windows.h>

namespace cloud
{
#define SERVER_IP "47.108.229.26"
#define SERVER_PORT 8888
	class Backup
	{
	private:
		std::string _back_dir;
		DataManager* _data;
	public:
		Backup(const std::string& back_dir, const std::string& backup_file)
			:_back_dir(back_dir)
		{
			_data = new DataManager(backup_file);
		}
		std::string GetFileIdentifier(const std::string& filename)
		{
			FileUtil fu(filename);
			std::stringstream ss;
			ss << fu.FileName() << "-" << fu.FileSize() << "-" << fu.LastMTime();
			return ss.str();
		}
		bool Upload(const std::string& filename)
		{
			FileUtil fu(filename);
			std::string body;
			fu.GetContent(&body);
			httplib::Client client(SERVER_IP, SERVER_PORT);
			httplib::MultipartFormData item;
			item.content = body;
			item.filename = fu.FileName();
			item.name = "file";
			item.content_type = "application/octet-stream";
			httplib::MultipartFormDataItems items;
			items.push_back(item);
			auto ret = client.Post("/upload", items);
			if (!ret || ret->status != 200)
			{
				return false;
			}
			return true;
		}
		bool IsNeedUpload(const std::string& filename)
		{
			std::string id;
			if (_data->GetOnebykey(filename, &id) != false)
			{
				std::string new_id = GetFileIdentifier(filename);
				if (id == new_id)
				{
					return false;
				}
			}
			FileUtil fu(filename);
			if (time(nullptr) - fu.LastMTime() < 3)
			{
				return false;
			}
			return true;
		}
		bool RunModule()
		{
			while (true)
			{
				FileUtil fu(_back_dir);
				std::vector<std::string> arry;
				fu.GetDirectory(&arry);
				for (auto& a : arry)
				{
					if (IsNeedUpload(a))
					{
						if (Upload(a))
						{
							_data->Insert(a, GetFileIdentifier(a));
						}
					}
				}
				Sleep(1);
			}
			return true;
		}
	};
}